﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Quakk
{
    public class Configuration
    {
        private const string configurationFileName = "Configuration.xml";

        public string Username
        {
            get;
            set;
        }

        public string Password
        {
            get;
            set;
        }

        /// <summary>
        /// Load the Configuration file and return it as a Configuration object
        /// </summary>
        /// <returns>The Configuration</returns>
        public static Configuration LoadConfiguration()
        {
            string appPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Quakk");
            string filePath = Path.Combine(appPath, configurationFileName);

            Configuration config = null;
            XmlSerializer serializer = new XmlSerializer(typeof(Configuration));

            if (File.Exists(filePath))
            {
                Stream stream = File.OpenRead(filePath);

                try
                {
                    config = (Configuration) serializer.Deserialize(stream);
                }
                finally
                {
                    stream.Close();
                }
            }

            return config;
        }

        /// <summary>
        /// Saves the Configuration
        /// </summary>
        public void Save()
        {
            string appPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Quakk");
            string filePath = Path.Combine(appPath, configurationFileName);

            if(!Directory.Exists(appPath))
            {
                Directory.CreateDirectory(appPath);
            }

            Stream stream = null;
            XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
            try
            {
                stream = File.Create(filePath);
                serializer.Serialize(stream, this);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
    }
}
